package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easyban.common.R;
import com.easyban.entity.Product;
import com.easyban.service.ProductService;
import com.easyban.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    private final String basePath = System.getProperty("user.dir") + File.separator + "upload" + File.separator;
    @Autowired
    ProductService productService;

    @GetMapping("/captcha")
    public R<String> createCaptcha(HttpServletRequest req) throws IOException {
        Map<String, String> captchaMap = ValidateCodeUtils.createCaptcha();

        // 获取验证码和图片
        String code = captchaMap.keySet().iterator().next();
        String image = captchaMap.get(code);

        req.getSession().setAttribute("code", code);

        return R.success(image);
    }

    @GetMapping("/checkCaptcha")
    public R<String> checkCaptcha(HttpServletRequest req, String inputCode) throws IOException {
        String code = (String) req.getSession().getAttribute("code");
        log.info("用户输入的是：{}", inputCode);
        //大小写字母都行
        if (!code.isEmpty() && code.equalsIgnoreCase(inputCode)) {
            return R.success("1");
        }
        return R.success("0");
    }


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info("文件名是：{}", file.toString());

        // 创建上传目录
        File uploadDirFile = new File(basePath);
        if (!uploadDirFile.exists()) {
            uploadDirFile.mkdirs();
        }

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        // 存储文件到指定目录
        File destFile = new File(basePath, fileName);

        try {
            //将临时文件转存到指定位置
            file.transferTo(destFile);
        } catch (IOException e) {
            log.error(e.getMessage());
            return R.error("上传失败");
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(@RequestParam String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //根据文件后缀名设置响应内容类型
            String suffix = name.substring(name.lastIndexOf("."));
            switch (suffix.toLowerCase()) {
                case ".jpg":
                case ".jpeg":
                    response.setContentType("image/jpeg");
                    break;
                case ".png":
                    response.setContentType("image/png");
                    break;
                default:
                    response.setContentType("application/octet-stream");
                    break;
            }

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @DeleteMapping("/photo")
    public R<String> deletePhoto(@RequestParam String photo) {
        log.info("开始删除：{}", photo);

        String uploadDir = System.getProperty("user.dir") + File.separator + "upload";

        // 构建要删除的文件的完整路径
        String filePathToDelete = uploadDir + File.separator + photo;

        // 创建一个 File 对象表示要删除的文件
        File fileToDelete = new File(filePathToDelete);

        // 检查要删除的文件是否存在
        if (fileToDelete.exists()) {
            // 尝试删除文件
            if (fileToDelete.delete()) {
                // 文件删除成功
                return R.success("文件删除成功");
            } else {
                // 文件删除失败
                return R.success("文件删除失败");
            }
        } else {
            // 要删除的文件不存在
            return R.success("要删除的文件不存在");
        }
    }


}
